package com.screen.screendisplay.service.impl.wholeproduct;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.screen.screendisplay.entity.al.AlProdoperSales;
import com.screen.screendisplay.mapper.al.AlProdoperSalesMapper;
import com.screen.screendisplay.service.wholeproduct.IWholeAlSalesService;
import com.screen.screendisplay.vo.wholeproduct.AluminumSalesVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * 铝业销售完成情况 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-10-12
 */
@Service
public class WholeAlSalesServiceImpl implements IWholeAlSalesService {

    private final AlProdoperSalesMapper alProdoperSalesMapper;

    public WholeAlSalesServiceImpl(AlProdoperSalesMapper alProdoperSalesMapper) {
        this.alProdoperSalesMapper = alProdoperSalesMapper;
    }

    @Override
    public List<AluminumSalesVO> getAluminumSales(Integer year) {
        // 1. 确定查询的年份范围
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        
        // 如果指定了年份，查询该年份及之前4年；否则查询最近5年
        int endYear = (year != null) ? year : currentYear;
        int startYear = endYear - 4;
        
        // 2. 查询指定年份范围内的所有销售数据
        QueryWrapper<AlProdoperSales> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("year", startYear)
                   .le("year", endYear)
                   .orderByAsc("year");
        List<AlProdoperSales> allData = alProdoperSalesMapper.selectList(queryWrapper);
        
        // 3. 按年份和品类分组，汇总计划销量和实际销量
        Map<Integer, Map<Byte, SalesAggregation>> yearCategoryMap = new HashMap<>();
        
        for (AlProdoperSales sales : allData) {
            int salesYear = sales.getYear();
            Byte salesCategory = sales.getSalesCategory();
            
            yearCategoryMap
                .computeIfAbsent(salesYear, k -> new HashMap<>())
                .computeIfAbsent(salesCategory, k -> new SalesAggregation())
                .add(sales.getMonthPlanSales(), sales.getMonthActualSales());
        }
        
        // 4. 构建结果列表（包含最近5年）
        List<AluminumSalesVO> resultList = new ArrayList<>();
        for (int i = startYear; i <= endYear; i++) {
            AluminumSalesVO vo = new AluminumSalesVO();
            vo.setYear(i);
            
            Map<Byte, SalesAggregation> categoryMap = yearCategoryMap.get(i);
            
            if (categoryMap != null) {
                // 计算铝液完成率（品类0）
                SalesAggregation liquidSales = categoryMap.get((byte) 0);
                if (liquidSales != null) {
                    BigDecimal completionRate = liquidSales.calculateCompletionRate();
                    vo.setLiquidAluminumCompletionRate(completionRate);
                } else {
                    vo.setLiquidAluminumCompletionRate(BigDecimal.ZERO);
                }
                
                // 计算铝锭完成率（品类1）
                SalesAggregation ingotSales = categoryMap.get((byte) 1);
                if (ingotSales != null) {
                    BigDecimal completionRate = ingotSales.calculateCompletionRate();
                    vo.setAluminumIngotCompletionRate(completionRate);
                } else {
                    vo.setAluminumIngotCompletionRate(BigDecimal.ZERO);
                }
            } else {
                // 没有数据，设置为0
                vo.setLiquidAluminumCompletionRate(BigDecimal.ZERO);
                vo.setAluminumIngotCompletionRate(BigDecimal.ZERO);
            }
            
            resultList.add(vo);
        }
        
        // 5. 按年份排序（从旧到新）
        resultList.sort(Comparator.comparing(AluminumSalesVO::getYear));
        
        return resultList;
    }
    
    /**
     * 销售数据聚合类
     */
    private static class SalesAggregation {
        private BigDecimal totalPlan = BigDecimal.ZERO;
        private BigDecimal totalActual = BigDecimal.ZERO;
        
        public void add(BigDecimal plan, BigDecimal actual) {
            if (plan != null) {
                totalPlan = totalPlan.add(plan);
            }
            if (actual != null) {
                totalActual = totalActual.add(actual);
            }
        }
        
        public BigDecimal calculateCompletionRate() {
            if (totalPlan.compareTo(BigDecimal.ZERO) == 0) {
                return BigDecimal.ZERO;
            }
            // 完成率 = 实际销量 / 计划销量 * 100
            return totalActual
                    .divide(totalPlan, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
        }
    }
}

